<template>
  <div class="wrapper">
    <div id="app">
      <!-- 导航栏 -->
      <nav class="nav-bar">
        <div class="nav-left">
          <router-link to="/" class="nav-link">首页</router-link>
          <router-link to="/contact" class="nav-link">购物车</router-link>
          <router-link to="/about" class="nav-link">我的订单</router-link>
          <router-link to="/user" class="nav-link">我的</router-link>
        </div>
        <div class="nav-right">
          <template v-if="isLoggedIn">
            <div class="user-info">
              <span>{{ userInfo.name }}</span>
              <el-button type="text" @click="handleLogout">退出登录</el-button>
            </div>
          </template>
          <router-link to="/sign" class="nav-link" v-else>注册/登录</router-link>
        </div>
      </nav>

      <!-- 路由出口 + 个人信息内容 -->
      <div class="content">
        <router-view />

        <!-- 用户信息展示区域 -->
        <div v-if="isLoggedIn" class="user-profile">
          <div class="profile-header">
            <h3>个人信息</h3>
            <el-button type="primary" size="small" @click="openEditDialog">
              编辑信息
            </el-button>
          </div>
          
          <el-descriptions column="1" border class="info-card">
            <el-descriptions-item label="用户ID">{{ userInfo.id }}</el-descriptions-item>
            <el-descriptions-item label="用户名">{{ userInfo.name }}</el-descriptions-item>
            
            <!-- 密码项（带隐藏/显示功能） -->
            <el-descriptions-item label="密码">
              <div class="password-container">
                <span :class="{ 'password-hidden': !showPassword }">
                  {{ showPassword ? userInfo.password : '••••••••' }}
                </span>
                <el-button 
                  type="text" 
                  size="small" 
                  @click="showPassword = !showPassword"
                  class="toggle-btn"
                >
                  {{ showPassword ? '隐藏' : '显示' }}
                </el-button>
              </div>
            </el-descriptions-item>
            
            <el-descriptions-item label="电话">{{ userInfo.phone || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="地址">{{ userInfo.address || '未设置' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 未登录提示 -->
        <div v-else class="login-prompt">
          <el-empty description="请先登录查看个人信息">
            <template #bottom>
              <router-link to="/sign">
                <el-button type="primary">去登录</el-button>
              </router-link>
            </template>
          </el-empty>
        </div>
      </div>

      <!-- 编辑用户弹窗 -->
      <el-dialog v-model="editDialogVisible" title="编辑个人信息" width="600px">
        <el-form 
          :model="editFormData" 
          :rules="editRules" 
          ref="editFormRef"
          label-width="80px" 
          style="padding: 20px;"
        >
          <el-form-item label="用户名" prop="name">
            <el-input v-model="editFormData.name" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="新密码" prop="password">
            <el-input v-model="editFormData.password" placeholder="请输入新密码" type="password" />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="editFormData.confirmPassword" placeholder="请再次输入新密码" type="password" />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="editFormData.phone" placeholder="请输入电话" />
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="editFormData.address" placeholder="请输入地址" type="textarea" :rows="3" />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEditForm">提交</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElDescriptions, ElDescriptionsItem, ElEmpty, ElButton, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus';

export default {
  name: 'UserProfileView',
  components: {
    ElDescriptions,
    ElDescriptionsItem,
    ElEmpty,
    ElButton,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput
  },
  data() {
    return {
      isLoggedIn: false,
      userInfo: {}, // 存储用户信息：id, name, password, phone, address
      loginUserId: localStorage.getItem('userId') || null,
      showPassword: false, // 控制密码显示/隐藏
      
      // 编辑表单相关
      editDialogVisible: false,
      editFormData: {
        name: '',
        password: '',
        confirmPassword: '',
        phone: '',
        address: ''
      },
      editFormRef: null,
      editRules: {
        name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码格式', trigger: 'blur' }
        ],
        password: [
          { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: this.validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.checkLoginStatus();
  },
  methods: {
    // 检查登录状态并加载用户信息（增加容错处理）
    async checkLoginStatus() {
      try {
        const storedUserId = localStorage.getItem('userId');
        if (storedUserId) {
          this.loginUserId = storedUserId;
          await this.getUserInfo();
          this.isLoggedIn = true;
        } else {
          this.isLoggedIn = false;
        }
      } catch (err) {
        console.error('检查登录状态失败:', err);
        this.clearUserInfo();
        this.isLoggedIn = false;
      }
    },

    // 从后端获取用户信息
    async getUserInfo() {
      try {
        const res = await axios.get(`http://127.0.0.1:8080/users/${this.loginUserId}`);
        this.userInfo = {
          id: res.data.id,
          name: res.data.name,
          password: res.data.password || '',
          phone: res.data.phone,
          address: res.data.address
        };
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo));
      } catch (err) {
        ElMessage.error('获取用户信息失败');
        console.error('获取用户信息失败：', err);
        this.handleLogout();
      }
    },

    // 安全的退出登录方法（重点优化）
    handleLogout() {
      try {
        // 清除本地存储
        this.clearUserInfo();
        
        // 重置状态
        this.isLoggedIn = false;
        this.userInfo = {};
        this.loginUserId = null;
        
        // 显示成功消息并跳转
        ElMessage.success('已退出登录');
        this.$router.push('/').catch(err => {
          console.warn('路由跳转失败:', err);
        });
      } catch (err) {
        console.error('退出登录过程出错:', err);
        // 即使出错也确保状态正确
        this.isLoggedIn = false;
        this.userInfo = {};
        this.loginUserId = null;
        ElMessage.success('已退出登录');
      }
    },

    // 清除用户信息的工具方法
    clearUserInfo() {
      try {
        if (localStorage) {
          localStorage.removeItem('userInfo');
          localStorage.removeItem('userId');
        }
      } catch (err) {
        console.warn('清除本地存储失败:', err);
      }
    },

    // 打开编辑弹窗
    openEditDialog() {
      // 复制当前用户信息到表单
      this.editFormData = {
        name: this.userInfo.name || '',
        phone: this.userInfo.phone || '',
        address: this.userInfo.address || '',
        password: '',
        confirmPassword: ''
      };
      this.editDialogVisible = true;
    },

    // 验证确认密码
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.editFormData.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    },

    // 提交编辑表单
    submitEditForm() {
      if (!this.$refs.editFormRef) return;
      
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        
        try {
          // 准备要更新的数据
          const updateData = {
            name: this.editFormData.name,
            phone: this.editFormData.phone,
            address: this.editFormData.address
          };
          
          // 如果用户输入了新密码，则更新密码
          if (this.editFormData.password) {
            updateData.password = this.editFormData.password;
          }
          
          // 发送更新请求
          await axios.put(`http://127.0.0.1:8080/users/${this.loginUserId}`, updateData);
          
          // 更新本地数据
          this.userInfo.name = this.editFormData.name;
          this.userInfo.phone = this.editFormData.phone;
          this.userInfo.address = this.editFormData.address;
          if (this.editFormData.password) {
            this.userInfo.password = this.editFormData.password;
          }
          
          // 更新本地存储
          localStorage.setItem('userInfo', JSON.stringify(this.userInfo));
          
          ElMessage.success('修改成功');
          this.editDialogVisible = false;
        } catch (err) {
          ElMessage.error('修改失败');
          console.error(err);
        }
      });
    }
  }
}
</script>

<style scoped>
/* 页面容器 */
.wrapper {
  padding: 20px;
}
.content {
  padding-top: 60px;
  max-width: 800px;
  margin: 0 auto;
}

/* 导航栏样式 */
.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}
.nav-left, .nav-right {
  display: flex;
  gap: 20px;
}
.nav-link {
  text-decoration: none;
  color: #333;
  padding: 5px 10px;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
}
.nav-link.router-link-exact-active {
  color: #6b46c1;
  border-bottom-color: #6b46c1;
}

/* 用户信息区域样式 */
.user-profile {
  margin-bottom: 20px;
}
.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.profile-header h3 {
  color: #333;
  font-size: 18px;
  font-weight: 500;
  margin: 0;
}
.info-card {
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

/* 密码显示控制样式 */
.password-container {
  display: flex;
  align-items: center;
  gap: 10px;
}
.password-hidden {
  letter-spacing: 2px;
}
.toggle-btn {
  color: #6b46c1;
  padding: 0 5px;
}

/* 未登录提示样式 */
.login-prompt {
  margin-top: 50px;
  text-align: center;
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}
.user-info span {
  color: #333;
  font-weight: 500;
}

/* 描述列表样式优化 */
.el-descriptions__label {
  font-weight: 500;
  color: #666;
}
.el-descriptions__content {
  color: #333;
}
</style>